package com.lzyyj.gmis.base.webui;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Random;

/**
 * 获得验证码图像
 * @author YYJ
 *
 */
public class CheckCode extends HttpServlet {

	public CheckCode() {
		// TODO Auto-generated constructor stub
	}

	//Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        response.setContentType("image/jpeg"); //必须设置ContentType为image/jpeg
        response.setHeader("pragma", "no-cache");
        response.setHeader("cache-control", "no-cache");
        response.setHeader("expires", "0");
        
        int length = 4; //设置默认生成4个数字
        
        //可以在此加入保存验证码的代码
        HttpSession session = request.getSession();
        String checkCode = (String)session.getAttribute("CheckCode");
        if (checkCode==null||checkCode.equalsIgnoreCase("CheckCode")||request.getParameter("Refresh")!=null){
        	checkCode = null;
            if (request.getParameter("length") != null) {
                try {
                    length = Integer.parseInt(request.getParameter("length"));
                }
                catch (NumberFormatException e) {
                }
            }
            StringBuffer str = genCheckCode(length);
        	checkCode = str.toString();
            session.setAttribute("CheckCode", checkCode);
        }

        //创建内存图像
        int fontWidth =7;
        int fontHeight = 16;
        BufferedImage bufferedImage = new BufferedImage(fontWidth * length+8, fontHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufferedImage.createGraphics();
        g.clearRect(0, 0, 16, 40);
        g.setColor(Color.WHITE);
        g.drawString(checkCode, 4, 12);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "jpg", byteArrayOutputStream);
        OutputStream outputStream = response.getOutputStream();
        byte[] bytes = byteArrayOutputStream.toByteArray();
        outputStream.write(bytes);
        byteArrayOutputStream.close();
    }

	private StringBuffer genCheckCode(int length) {
		Date d = new Date();
        long lseed = d.getTime();
        java.util.Random r = new Random(lseed); //设置随机种子
        StringBuffer str = new StringBuffer();
        for (int i = 0; i < length; i++) {
            str.append(r.nextInt(9)); //生成随机数字
        }
		return str;
	}
}
